<?php

namespace Ignus\View\TokenParser;

use Ignus\View\TokenParser;
use Ignus\View\Error\Syntax;
use Ignus\View\Token;

class Set extends TokenParser
{
    public function parse(Token $token)
    {
        $lineno = $token->getLine();
        $stream = $this->parser->getStream();
        $names = $this->parser->getExpressionParser()->parseAssignmentExpression();
        $capture = false;

        if ($stream->test(Token::OPERATOR_TYPE, '=')) {
            $stream->next();
            $values = $this->parser->getExpressionParser()->parseMultitargetExpression();

            $stream->expect(Token::BLOCK_END_TYPE);

            if (count($names) !== count($values)) {
                throw new Syntax("When using set, you must have the same number of variables and assignements.", $lineno);
            }
        }
        else {
            $capture = true;

            if (count($names) > 1) {
                throw new Syntax("When using set with a block, you cannot have a multi-target.", $lineno);
            }

            $stream->expect(Token::BLOCK_END_TYPE);

            $values = $this->parser->subparse(array($this, 'decideBlockEnd'), true);
            $stream->expect(Token::BLOCK_END_TYPE);
        }

        return new \Ignus\View\Node\Set($capture, $names, $values, $lineno, $this->getTag());
    }

    public function decideBlockEnd(Token $token)
    {
        return $token->test('endset');
    }

    public function getTag()
    {
        return 'set';
    }
}
